﻿#include "headui.h"
#include "ui_headui.h"
#include "login.h"

HeadUI::HeadUI(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HeadUI)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);//将窗口标题去掉
    ui->listWidget->setIconSize(QSize(50,50));
}

HeadUI::~HeadUI()
{
    delete ui;
}

void HeadUI::init(QString path)
{
    QListWidgetItem* item = new QListWidgetItem(QIcon(path),QString(""));
    ui->listWidget->insertItem(0,item);
    m_vec.append(path);
}

void HeadUI::mousePressEvent(QMouseEvent *event)
{
    isPressedWidget = true; // 当前鼠标按下的是QWidget而非界面上布局的其它控件
    last = event->globalPos();
}

void HeadUI::mouseMoveEvent(QMouseEvent *event)
{
    if (isPressedWidget)
    {
        int dx = event->globalX() - last.x();
        int dy = event->globalY() - last.y();
        last = event->globalPos();
        move(x()+dx, y()+dy);
    }
}

void HeadUI::mouseReleaseEvent(QMouseEvent *event)
{
    int dx = event->globalX() - last.x();
    int dy = event->globalY() - last.y();
    move(x()+dx, y()+dy);
    isPressedWidget = false; // 鼠标松开时，置为false
}


void HeadUI::on_btn_save_clicked()//保存更改
{
    QString id = Widget::getInstance().getName();
    OpDb::getInstance().updateHead(id,m_path);
}



void HeadUI::on_listWidget_currentRowChanged(int currentRow)
{
    qDebug()<<m_vec[m_vec.size()-currentRow-1]<<endl;
    QString path = m_vec[m_vec.size()-currentRow-1];
    QPixmap pixmap(path);
    pixmap.scaled(300,250,Qt::IgnoreAspectRatio);
    ui->head_show->setScaledContents(true);
    ui->head_show->setPixmap(pixmap);
    m_path = m_vec[m_vec.size()-currentRow-1];
}

void HeadUI::on_toolButton_clicked()
{
    close();
    destroy();
}

void HeadUI::on_btn_upload_clicked()//上传头像
{
    QString file = QFileDialog::getOpenFileName(this, tr("Select an image"),
                                      ".", tr("Bitmap Files (*.bmp)\n"
                                        "JPEG (*.jpg *jpeg)\n"
                                        "GIF (*.gif)\n"
                                        "PNG (*.png)\n"));
    QFile file1(file);
    QFileInfo info(file);
    QPixmap pixmap;
    QString filename = info.fileName();
    if(file1.open(QIODevice::ReadOnly))
    {
        QString path = "D:\\QTCode5.14\\CClient\\res\\"+filename;
        QFile file2(path);
        if(file2.exists())return;
        if(!file2.open(QIODevice::WriteOnly))return;
        char buff[1024];
        while(!file1.atEnd())
        {
            memset(buff,0,1024);
            file1.read(buff,1024);
            file2.write(buff,1024);
        }
        pixmap.load(path);
        m_path = path;
        file2.close();
    }
    file1.close();
    pixmap.scaled(300,250,Qt::IgnoreAspectRatio);
    ui->head_show->setScaledContents(true);
    ui->head_show->setPixmap(pixmap);
    qDebug()<<file;
}
